package com.atguigu.gmall.list.receiver;

import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.rabbit.config.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 搜索模块监听器类
 *
 * @author: atguigu
 * @create: 2023-08-11 15:55
 */
@Slf4j
@Component
public class ListReceiver {

    @Autowired
    private SearchService searchService;


    /**
     * 监听商品上架消息，完成索引库新增商品
     *
     * @param skuId
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER, durable = "true"),
            key = MqConst.ROUTING_GOODS_UPPER
    ))
    public void processGoodsUpper(Long skuId, Channel channel, Message message) {
        if (skuId != null) {
            log.info("[搜素服务]监听到商品上架，商品ID：{}", skuId);
            //1.业务处理：完成索引库新增文档
            searchService.upperGoods(skuId);
            //2.手动应答MQ
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }


    /**
     * 监听商品下架消息，完成索引库删除
     *
     * @param skuId
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER, durable = "true"),
            key = MqConst.ROUTING_GOODS_LOWER
    ))
    public void processGoodsLower(Long skuId, Channel channel, Message message) {
        if (skuId != null) {
            log.info("[搜素服务]监听到商品下架，商品ID：{}", skuId);
            //1.业务处理：完成索引库新增文档
            searchService.lowerGoods(skuId);
            //2.手动应答MQ
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
